import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class JedisHash {

    private static void test1(Jedis jedis) {
        System.out.println("-----------------------------------");
        System.out.println("hset 和 hget");
        jedis.flushAll();

        jedis.hset("key1", "f1", "v1");
        String result = jedis.hget("key1", "f1");

        System.out.println("result: " + result);

        Map<String, String> map = new HashMap<>();
        map.put("f1", "v1");
        map.put("f2", "v2");
        map.put("f3", "v3");

        jedis.hset("key2", map);
        System.out.println("key2: " + jedis.hgetAll("key2"));

    }

    private static void test2(Jedis jedis) {
        System.out.println("-----------------------------------");
        System.out.println("hexists");
        jedis.flushAll();

        jedis.hset("key1", "f1", "v1");

        boolean result1 = jedis.hexists("key1", "f1");
        boolean result2 = jedis.hexists("key1", "f2");
        System.out.println("result1: " + result1);
        System.out.println("result2: " + result2);
    }

    private static void test3(Jedis jedis) {
        System.out.println("-----------------------------------");
        System.out.println("hdel");
        jedis.flushAll();

        jedis.hset("key1", "f1", "v1");
        jedis.hset("key1", "f2", "v2");
        jedis.hset("key1", "f3", "v3");

        long result = jedis.hdel("key1", "f1");
        System.out.println("result: " + result);

        System.out.println("f1: " + jedis.hget("key1", "f1"));
        System.out.println("f2: " + jedis.hget("key1", "f2"));
        System.out.println("f3: " + jedis.hget("key1", "f3"));
    }

    private static void test4(Jedis jedis) {
        System.out.println("-----------------------------------");
        System.out.println("hkeys 和 hvals");
        jedis.flushAll();

        Map<String, String> map = new HashMap<>();
        map.put("f1", "v1");
        map.put("f2", "v2");
        map.put("f3", "v3");

        jedis.hmset("key1", map);
        Set<String> set = jedis.hkeys("key1");
        List<String> list = jedis.hvals("key1");
        System.out.println("key1 -> field:" + set);
        System.out.println("key2 -> value:" + list);
    }

    public static void main(String[] args) {
        JedisPool jedisPool = new JedisPool("tcp://127.0.0.1:8888");
        try(Jedis jedis = jedisPool.getResource()) {
            test1(jedis);
            test2(jedis);
            test3(jedis);
            test4(jedis);
        }
    }

}
